<?php
	class Thaind_Plugins_Acl extends Zend_Controller_Plugin_Abstract{
  	 	protected $_acl;
		public function preDispatch(Zend_Controller_Request_Abstract $request){
			$module_name = $request->getModuleName();
			$controller_name = $request->getControllerName();
			$action_name = $request->getActionName();
			if (in_array($module_name, array("admin"))){
				$auth = Thaind_Auth_Admin::getInstance();
				$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
				$cache = $bootstrap->getResource('cache');
				if ($cache){
					if(!$acl = $cache->load('acl')) {
						$acl = new Thaind_Acl($auth);
						$this->_acl = $acl;
						$cache->save($acl,"acl",array(),2592000);
					}else{
						$this->_acl = $acl;
					}
				}else{
					$acl = new Thaind_Acl($auth);
					$this->_acl = $acl;
				}
				$identity = $auth->getIdentity();
				$request = $this->getRequest();
				if ($auth->hasIdentity()){
					$role = $identity->username;
					if ($this->_acl->has($module_name . ":" . $controller_name)){
						if(!$this->_acl->isAllowed($role,$module_name . ":" . $controller_name,$action_name)){
			         		$request->setActionName('error');
			         		$request->setControllerName('error');
			         		$request->setModuleName('admin');
						}
					}
				}else{
					if ($controller_name != "index"){
		         		$request->setActionName('login');
		         		$request->setControllerName('index');
		         		$request->setModuleName('admin');
					}
				}
			}
		}
	}

